<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>刮刮卡 v2 自动显示</title>
<style>
body {
    margin:0;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
    background: #d4f7dc;
    font-family: "Verdana";
}
.card-container{
    position:relative;
    width:400px; height:300px;
    border:5px solid #4caf50;
    border-radius:10px;
    overflow:hidden;
}
.card-container img{
    width:100%; height:100%;
}
canvas{
    position:absolute; top:0; left:0;
    cursor:crosshair;
}
.hint{
    position:absolute;
    bottom:10px; right:10px;
    background:rgba(76,175,80,0.7);
    color:white;
    padding:4px 8px;
    border-radius:5px;
    font-size:14px;
}
</style>
</head>
<body>
<div class="card-container">
    <img src="./images/prize3.jpg" alt="奖励图片">
    <canvas id="canvas" width="400" height="300"></canvas>
</div>
<script>
const canvas=document.getElementById("canvas");
const ctx=canvas.getContext("2d");

// 绘制涂层
ctx.fillStyle="#8fd9a8"; 
ctx.fillRect(0,0,canvas.width,canvas.height);

let isComplete=false;

// 检查刮开比例
function checkScratched(){
    const imgData = ctx.getImageData(0,0,canvas.width,canvas.height);
    let cleared=0;
    for(let i=3;i<imgData.data.length;i+=4){
        if(imgData.data[i]===0) cleared++;
    }
    const percent=cleared/(canvas.width*canvas.height)*100;
    if(percent>30 && !isComplete){ // 刮开30%自动显示
        isComplete=true;
        ctx.clearRect(0,0,canvas.width,canvas.height);
    }
}

// 鼠标刮
canvas.addEventListener("mousemove",e=>{
    if(e.buttons===1 && !isComplete){
        const r=canvas.getBoundingClientRect();
        const x=e.clientX-r.left;
        const y=e.clientY-r.top;
        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.arc(x,y,10,0,Math.PI*2);
        ctx.fill();
        checkScratched();
    }
});

// 触屏刮
canvas.addEventListener("touchmove",e=>{
    e.preventDefault();
    if(!isComplete){
        const r=canvas.getBoundingClientRect();
        const t=e.touches[0];
        const x=t.clientX-r.left;
        const y=t.clientY-r.top;
        ctx.globalCompositeOperation="destination-out";
        ctx.beginPath();
        ctx.arc(x,y,10,0,Math.PI*2);
        ctx.fill();
        checkScratched();
    }
},{passive:false});
</script>
</body>
</html>
